package com.heisen.base.config;

import com.heisen.base.utils.SpringUtils;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author sen
 * @description  异步任务管理器
 * @date 2024/1/8 14:35
 */

public class AsyncManager {

    /**
     * 操作延迟1000毫秒
     */
    private final int OPERATE_DELAY_TIME = 1000;

    /**
     * 异步操作任务调度线程池  执行周期性或定时任务
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行任务
     * @param task 任务
     * @param operateDelayTime  周期性时间
     */
    public void execute(TimerTask task,Integer operateDelayTime){
        if(operateDelayTime == null){
            operateDelayTime = OPERATE_DELAY_TIME;
        }
        executor.schedule(task, operateDelayTime, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
